<!--
 * @Description:It is troublesome to implement radio button group in the form. So it is extracted independently as a separate component
-->
<template>
  <RadioGroup
    v-if="viewMode === 'edit'"
    v-bind="attrs"
    v-model:value="innerValue"
    button-style="solid"
    @change="handleClick"
  >
    <template v-for="item in getOptions" :key="`${item.value}`">
      <RadioButton
        v-if="props.isBtn"
        :value="item.value"
        :disabled="item.disabled"
        @click="handleClick(item)"
      >
        {{ item.label }}
      </RadioButton>
      <Radio
        v-else
        :value="item.value"
        :disabled="item.disabled"
        @click="handleClick(item)"
      >
        {{ item.label }}
      </Radio>
    </template>
  </RadioGroup>
  <div v-else v-bind="$attrs">{{ label }}</div>
</template>
<script lang="ts">
import {
  defineComponent,
  PropType,
  ref,
  watchEffect,
  computed,
  unref,
  watch,
} from 'vue';
import { Radio } from 'ant-design-vue';
import { isFunction, isString } from '@/utils/is';
import { useAttrs } from '@/hooks/core/useAttrs';
import { propTypes } from '@/utils/propTypes';
import { get, omit } from 'lodash-es';
import { useI18n } from '@/hooks/web/useI18n';
import { getDictList } from '@/utils/cache/busCache';
import { FormMode } from '@/enums/appEnum';

type OptionsItem = {
  label: string;
  value: string | number | boolean;
  disabled?: boolean;
};

export default defineComponent({
  name: 'ApiRadioGroup',
  components: {
    RadioGroup: Radio.Group,
    RadioButton: Radio.Button,
    Radio,
  },
  props: {
    api: {
      type: Function as PropType<
        (arg?: Recordable | string) => Promise<OptionsItem[]>
      >,
      default: null,
    },
    params: {
      type: [Object, String] as PropType<Recordable | string>,
      default: () => ({}),
    },
    value: {
      type: [String, Number, Boolean] as PropType<string | number | boolean>,
    },
    isBtn: {
      type: [Boolean] as PropType<boolean>,
      default: false,
    },
    viewMode: {
      type: String as PropType<FormMode>,
      default: 'edit',
    },
    numberToString: propTypes.bool,
    resultField: propTypes.string.def(''),
    labelField: propTypes.string.def('label'),
    valueField: propTypes.string.def('value'),
    immediate: propTypes.bool.def(true),
    dictCode: propTypes.string.def(''),
  },
  emits: ['options-change', 'change', 'update:value'],
  setup(props, { emit }) {
    const options = ref<OptionsItem[]>([]);
    const loading = ref(false);
    const isFirstLoad = ref(true);
    const attrs = useAttrs();
    const { t } = useI18n();
    const label = ref('');
    const innerValue = ref();
    // Processing options value
    const getOptions = computed(() => {
      const { labelField, valueField, numberToString } = props;

      return unref(options).reduce((prev, next: Recordable) => {
        if (next) {
          const value = next[valueField];
          prev.push({
            label: next[labelField],
            value: numberToString ? `${value}` : value,
            ...omit(next, [labelField, valueField]),
          });
        }
        return prev;
      }, [] as OptionsItem[]);
    });

    watchEffect(() => {
      props.immediate && fetch();
    });

    const getLabel = () => {
      setTimeout(() => {
        const { labelField, valueField } = props;
        const opts = options.value;
        if (!opts || opts.length === 0) return '';
        if (innerValue.value && isString(innerValue.value)) {
          const findOption = opts.find(
            (option) => option[valueField] + '' === innerValue.value + ''
          );
          label.value = findOption ? findOption[labelField] : '';
        }
      }, 300);
    };
    watch(
      () => options.value,
      (v) => {
        if (v) getLabel();
      },
      {
        immediate: true,
      }
    );
    watch(
      () => props.value,
      (n) => {
        innerValue.value = n
      },
      { deep: true, immediate: true }
    );
    watch(
      () => props.dictCode,
      (v) => {
        options.value = getDictList(v);
      }
    );
    watch(
      () => props.params,
      () => {
        !unref(isFirstLoad) && fetch();
      },
      { deep: true }
    );

    async function fetch() {
      if (props.dictCode) {
        options.value = getDictList(props.dictCode);
        emitChange();
        return;
      }
      const api = props.api;
      if (!api || !isFunction(api)) return;
      options.value = [];
      try {
        loading.value = true;
        const res = await api(props.params);
        if (Array.isArray(res)) {
          options.value = res;
          emitChange();
          return;
        }
        if (props.resultField) {
          options.value = get(res, props.resultField) || [];
        }
        emitChange();
      } catch (error) {
        console.warn(error);
      } finally {
        loading.value = false;
      }
    }

    function emitChange() {
      emit('options-change', unref(getOptions));
    }

    function handleClick(e: Event) {
      const target = e.target as HTMLInputElement;
      emit('update:value', target.value as string, e);
      emit('change', target.value, e);
    }

    return {
      innerValue,
      label,
      getOptions,
      attrs,
      loading,
      t,
      handleClick,
      props,
    };
  },
});
</script>
